<template>
  <div style="margin-top:70px">
    <upload-excel :on-success="handleSuccess" :before-upload="beforeUpload" />
  </div>
</template>

<script>
import { formatExcelDate } from '@/utils'
import { importEmployees } from '@/api/employees'

export default {
  name: 'Import',
  methods: {
    beforeUpload(file) {
      const isLt1M = file.size / 1024 / 1024 < 1
      if (isLt1M) {
        return true
      }
      this.$message({
        message: 'Please do not upload files larger than 1m in size.',
        type: 'warning'
      })
      return false
    },
    async handleSuccess({ results, header }) {
      // console.log(results, header)
      // console.log(this.transEmployees(results))
      // 点击导入，获取数据
      const data = this.transEmployees(results)
      try {
        const res = await importEmployees(data)
        this.$message.success(res.message)
        this.$router.back()
      } catch (e) {
        this.$message.error(e.message)
      }
    },
    // 把获取到数组转换为对应的英文key
    // 在这里处理函数，再上面调用
    transEmployees(results) {
      const mapInfo = {
        '入职日期': 'timeOfEntry',
        '手机号': 'mobile',
        '姓名': 'username',
        '转正日期': 'correctionTime',
        '工号': 'workNumber',
        '部门': 'departmentName',
        '聘用形式': 'formOfEmployment'
      }
      return results.map(zhobj => {
      // 得到每一个中文的key值
        const enkeys = {}
        const zhkeys = Object.keys(zhobj)
        // 循环得到每一个中文key换到英文key上面去
        zhkeys.forEach(zhkey => {
          const enkey = mapInfo[zhkey]
          if (enkey === 'timeOfEntry' || enkey === 'correctionTime') {
            enkeys[enkey] = formatExcelDate(zhobj[zhkey])
          } else {
            enkeys[enkey] = zhobj[zhkey]
          }
        })
        return enkeys
      })
    }
  }
}

</script>

<style lang="less" scoped>

</style>
